package com.sdau.repairmaster.UIFile;



import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.sdau.repairmaster.R;
import com.sdau.repairmaster.logic.tools.UserUtils;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import FunctionalModule.PasswordStrength;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static java.lang.Thread.sleep;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener, View.OnFocusChangeListener, TextWatcher {

    private String TAG = "ifu25";
    private final int FAILURE_CODE=1001;//失败
    private final int SUCCESS_CODE=1000;//成功

    //自动登录选项
    private CheckBox autoLogin;

    private PasswordStrength passwordStrength;
    private EditText mEtLoginUsername;
    private EditText mEtLoginPwd;
    private LinearLayout mLlLoginUsername;
    private ImageView mIvLoginUsernameDel;
    private Button mBtLoginSubmit;
    private LinearLayout mLlLoginPwd;
    private ImageView mIvLoginPwdDel;
    private ImageView mIvLoginLogo;

    private TextView mTvLoginForgetPwd;

    //全局Toast
    private Toast mToast;

    //private int mLogoHeight;
    //private int mLogoWidth;

    /*
        看数据库中是否存在该账户以及密码是否正确
     */
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SUCCESS_CODE://成功
                    String data= (String) msg.obj;
                    if("true".equals(data.trim()))
                        loginSuccess();
                    else
                        loginFaile();
                    break;
                case FAILURE_CODE://失败
                    showToast("网络异常");
                    break;

            }
        }
    };

    /*
    点击忘记密码时，检验是否存在此账户
     */
    private Handler handler2=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SUCCESS_CODE://成功
                    String data= (String) msg.obj;
                    if("true".equals(data.trim())) {
                        //记录账号
                        storeAccount();

                        findUserHavePhone();
                    }
                    else
                        showToast("不存在此账号");
                    break;
                case FAILURE_CODE://失败
                    showToast("网络异常");
                    break;

            }
        }
    };

    /*
    看此账户有没有手机号
    */
    private Handler handler3=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case SUCCESS_CODE://成功
                    String data= (String) msg.obj;
                    if(!"false".equals(data.trim()))
                        startActivity(new Intent(LoginActivity.this,ForgetPwdActivity_one.class)
                                .putExtra("phone",data));
                    else
                        showToast("您的密码为初始密码，请联系校方");
                    break;
                case FAILURE_CODE://失败
                    showToast("网络异常");
                    break;

            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initView();
        //findViewById(R.id.ib_navigation_back).setOnClickListener(this);

//        mEtLoginUsername.setText("2018512649");
//        mEtLoginPwd.setText("512649");

    }




    //初始化视图
    private void initView() {



        //logo
        mIvLoginLogo = findViewById(R.id.iv_login_logo);

        //username
        mLlLoginUsername = findViewById(R.id.ll_login_username);
        mEtLoginUsername = findViewById(R.id.et_login_username);
        mIvLoginUsernameDel = findViewById(R.id.iv_login_username_del);

        //passwd
        mLlLoginPwd = findViewById(R.id.ll_login_pwd);
        mEtLoginPwd = findViewById(R.id.et_login_pwd);
        mIvLoginPwdDel = findViewById(R.id.iv_login_pwd_del);

        //提交
        mBtLoginSubmit = findViewById(R.id.bt_login_submit);

        //忘记密码
        mTvLoginForgetPwd = findViewById(R.id.tv_login_forget_pwd);

        //自动登录
        autoLogin = (CheckBox) findViewById(R.id.cb_remember_login) ;


        //注册点击事件


        mEtLoginUsername.setOnClickListener(this);
        mIvLoginUsernameDel.setOnClickListener(this);

        mEtLoginPwd.setOnClickListener(this);
        mIvLoginPwdDel.setOnClickListener(this);

        mTvLoginForgetPwd.setOnClickListener(this);

        mBtLoginSubmit.setOnClickListener(this);
        //注册其它事件
        mEtLoginUsername.setOnFocusChangeListener(this);
        mEtLoginUsername.addTextChangedListener(this);
        mEtLoginPwd.setOnFocusChangeListener(this);
        mEtLoginPwd.addTextChangedListener(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.et_login_username:
                mEtLoginPwd.clearFocus();
                mEtLoginUsername.setFocusableInTouchMode(true);
                mEtLoginUsername.requestFocus();
                break;
            case R.id.et_login_pwd:
                mEtLoginUsername.clearFocus();
                mEtLoginPwd.setFocusableInTouchMode(true);
                mEtLoginPwd.requestFocus();
                break;
            case R.id.iv_login_username_del:
                //清空用户名
                mEtLoginUsername.setText(null);
                break;
            case R.id.iv_login_pwd_del:
                //清空密码
                mEtLoginPwd.setText(null);
                break;
            case R.id.bt_login_submit:
                //登录

                onLoginSubmit();
                break;

            case R.id.tv_login_forget_pwd:
                //忘记密码
                forgetPwd();
                break;
         /*   case R.id.ll_login_layer:
            case R.id.ll_login_pull:
                mLlLoginPull.animate().cancel();
                mLlLoginLayer.animate().cancel();

                int height = mLlLoginOptions.getHeight();
                float progress = (mLlLoginLayer.getTag() != null && mLlLoginLayer.getTag() instanceof Float) ? (float) mLlLoginLayer.getTag() : 1;
                int time = (int) (360 * progress);

                if (mLlLoginPull.getTag() != null) {
                    mLlLoginPull.setTag(null);
                    glide(height, progress, time);
                } else {
                    mLlLoginPull.setTag(true);
                    upGlide(height, progress, time);
                }
                break;*/
            default:
                break;
        }
    }

    //用户名密码焦点改变
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        int id = v.getId();

        if (id == R.id.et_login_username) {
            if (hasFocus) {
                mLlLoginUsername.setActivated(true);
                mLlLoginPwd.setActivated(false);
            }
        } else {
            if (hasFocus) {
                mLlLoginPwd.setActivated(true);
                mLlLoginUsername.setActivated(false);
            }
        }
    }

    /**
     * menu glide
     *
     //* @param height   height
     //  * @param progress progress
     // * @param time     time
     */
  /*  private void glide(int height, float progress, int time) {
        mLlLoginPull.animate()
                .translationYBy(height - height * progress)
                .translationY(height)
                .setDuration(time)
                .start();

        mLlLoginLayer.animate()
                .alphaBy(1 * progress)
                .alpha(0)
                .setDuration(time)
                .setListener(new AnimatorListenerAdapter() {

                    @Override
                    public void onAnimationCancel(Animator animation) {
                        if (animation instanceof ValueAnimator) {
                            mLlLoginLayer.setTag(((ValueAnimator) animation).getAnimatedValue());
                        }
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        if (animation instanceof ValueAnimator) {
                            mLlLoginLayer.setTag(((ValueAnimator) animation).getAnimatedValue());
                        }
                        mLlLoginLayer.setVisibility(View.GONE);
                    }
                })
                .start();
    }

    /**
     * menu up glide
     *
     * @param height   height
     * @param progress progress
     * @param time     time

    private void upGlide(int height, float progress, int time) {
        mLlLoginPull.animate()
                .translationYBy(height * progress)
                .translationY(0)
                .setDuration(time)
                .start();
        mLlLoginLayer.animate()
                .alphaBy(1 - progress)
                .alpha(1)
                .setDuration(time)
                .setListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationStart(Animator animation) {
                        mLlLoginLayer.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {
                        if (animation instanceof ValueAnimator) {
                            mLlLoginLayer.setTag(((ValueAnimator) animation).getAnimatedValue());
                        }
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        if (animation instanceof ValueAnimator) {
                            mLlLoginLayer.setTag(((ValueAnimator) animation).getAnimatedValue());
                        }
                    }
                })
                .start();
    }

    //显示或隐藏logo
    @Override
    public void onGlobalLayout() {
        final ImageView ivLogo = this.mIvLoginLogo;
        Rect KeypadRect = new Rect();

        mLayBackBar.getWindowVisibleDisplayFrame(KeypadRect);

        int screenHeight = mLayBackBar.getRootView().getHeight();
        int keypadHeight = screenHeight - KeypadRect.bottom;

        //隐藏logo
        if (keypadHeight > 300 && ivLogo.getTag() == null) {
            final int height = ivLogo.getHeight();
            final int width = ivLogo.getWidth();
            this.mLogoHeight = height;
            this.mLogoWidth = width;

            ivLogo.setTag(true);

            ValueAnimator valueAnimator = ValueAnimator.ofFloat(1, 0);
            valueAnimator.setDuration(400).setInterpolator(new DecelerateInterpolator());
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float animatedValue = (float) animation.getAnimatedValue();
                    ViewGroup.LayoutParams layoutParams = ivLogo.getLayoutParams();
                    layoutParams.height = (int) (height * animatedValue);
                    layoutParams.width = (int) (width * animatedValue);
                    ivLogo.requestLayout();
                    ivLogo.setAlpha(animatedValue);
                }
            });

            if (valueAnimator.isRunning()) {
                valueAnimator.cancel();
            }
            valueAnimator.start();
        }
        //显示logo
        else if (keypadHeight < 300 && ivLogo.getTag() != null) {
            final int height = mLogoHeight;
            final int width = mLogoWidth;

            ivLogo.setTag(null);

            ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
            valueAnimator.setDuration(400).setInterpolator(new DecelerateInterpolator());
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float animatedValue = (float) animation.getAnimatedValue();
                    ViewGroup.LayoutParams layoutParams = ivLogo.getLayoutParams();
                    layoutParams.height = (int) (height * animatedValue);
                    layoutParams.width = (int) (width * animatedValue);
                    ivLogo.requestLayout();
                    ivLogo.setAlpha(animatedValue);
                }
            });

            if (valueAnimator.isRunning()) {
                valueAnimator.cancel();
            }
            valueAnimator.start();
        }
    }
*/
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    //用户名密码输入事件
    @Override
    public void afterTextChanged(Editable s) {
        String username = mEtLoginUsername.getText().toString().trim();
        String pwd = mEtLoginPwd.getText().toString().trim();

        //是否显示清除按钮
        if (username.length() > 0) {
            mIvLoginUsernameDel.setVisibility(View.VISIBLE);
        } else {
            mIvLoginUsernameDel.setVisibility(View.INVISIBLE);
        }
        if (pwd.length() > 0) {
            mIvLoginPwdDel.setVisibility(View.VISIBLE);
        } else {
            mIvLoginPwdDel.setVisibility(View.INVISIBLE);
        }

        //登录按钮是否可用
        if (!TextUtils.isEmpty(pwd) && !TextUtils.isEmpty(username)) {
            mBtLoginSubmit.setBackgroundResource(R.drawable.bg_login_submit);
            mBtLoginSubmit.setTextColor(getResources().getColor(R.color.white));
        } else {
            mBtLoginSubmit.setBackgroundResource(R.drawable.bg_login_submit_lock);
            mBtLoginSubmit.setTextColor(getResources().getColor(R.color.account_lock_font_color));
        }
    }

    /*
    登录按钮触发的事件
     */

    public void onLoginSubmit(){
        String account = mEtLoginUsername.getText().toString();
        String pwd = mEtLoginPwd.getText().toString();

        findUserByAccountAndPwd(account,pwd);
        /*
        if(mEtLoginPwd.getText().toString().equals("123456")&&mEtLoginUsername.getText().toString().equals("123"))  //连接数据库，获取密码账号
        {

            passwordStrength=new PasswordStrength(mEtLoginPwd.getText().toString());
            if(passwordStrength.Score()<=60)
            {
                startActivity(new Intent(LoginActivity.this, RegisterActivity_one.class));
            }
            else{
                startActivity(new Intent(LoginActivity.this, HomeActivity.class));
            }
        }

        else
            Toast.makeText(LoginActivity.this,"账号或密码输入不正确", Toast.LENGTH_SHORT).show();

         */
    }



    /*
     查看数据库中有没有此账号以及密码是否正确
     */
    public void findUserByAccountAndPwd(final String account,final String pwd){
        final String URL_login = "http://10.0.2.2:8080/RepairAdmin/userServlet";
        final Message message=Message.obtain();

        OkHttpClient okHttpClient  = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10,TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();



        RequestBody requestBody = new FormBody.Builder()
                .add("account", account)
                .add("pwd",pwd)
                .add("flag","findUserByAccountAndPwd")
                .build();


        final OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(URL_login)
                .post(requestBody)
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                message.what=FAILURE_CODE;
                message.obj=e.getMessage();//失败的信息
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String data=response.body().string();
                message.what=SUCCESS_CODE;
                message.obj=data;
                handler.sendMessage(message);

            }
        });

    }

    public void loginSuccess(){
        String account = mEtLoginUsername.getText().toString().trim();
        String pwd = mEtLoginPwd.getText().toString().trim();

        //记录账号
        SharedPreferences.Editor editor =
                getSharedPreferences("data",MODE_PRIVATE).edit();
        editor.putString("account",account);
        editor.apply();

        if(UserUtils.checkPwdIsNum(pwd)){//如果是纯数字，说明是初始密码
            startActivity(new Intent(LoginActivity.this, RegisterActivity_one.class)
                    .putExtra("account",account));
        }
        else {//否则不是初始密码
            startActivity(new Intent(LoginActivity.this, HomeActivity.class));
        }

    }

    public void loginFaile(){
        Toast.makeText(LoginActivity.this,"账号或密码输入不正确",
                Toast.LENGTH_SHORT).show();
    }


    /*
    查看有没有账号
     */
    public void forgetPwd(){
        final String URL_login = "http://10.0.2.2:8080/RepairAdmin/userServlet";
        final Message message=Message.obtain();

        String account = mEtLoginUsername.getText().toString();
        if("".equals(account)){
            showToast("请输入账号");
            return ;
        }

        OkHttpClient okHttpClient  = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10,TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();



        RequestBody requestBody = new FormBody.Builder()
                .add("account", account)
                .add("flag","findUserByAccount")
                .build();


        final OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(URL_login)
                .post(requestBody)
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                message.what=FAILURE_CODE;
                message.obj=e.getMessage();//失败的信息
                handler2.sendMessage(message);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String data=response.body().string();
                message.what=SUCCESS_CODE;
                message.obj=data;
                handler2.sendMessage(message);

            }
        });

    }
    /*
    查看有没有电话号码
     */
    public void findUserHavePhone(){
        final String URL_login = "http://10.0.2.2:8080/RepairAdmin/userServlet";
        final Message message=Message.obtain();

        String account = mEtLoginUsername.getText().toString();

        OkHttpClient okHttpClient  = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10,TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();



        RequestBody requestBody = new FormBody.Builder()
                .add("account", account)
                .add("flag","findUserHavePhone")
                .build();


        final OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(URL_login)
                .post(requestBody)
                .build();


        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                message.what=FAILURE_CODE;
                message.obj=e.getMessage();//失败的信息
                handler3.sendMessage(message);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String data=response.body().string();
                message.what=SUCCESS_CODE;
                message.obj=data;
                handler3.sendMessage(message);

            }
        });
    }

    public void storeAccount(){
        //记录账号
        SharedPreferences.Editor editor =
                getSharedPreferences("data",MODE_PRIVATE).edit();
        editor.putString("account",mEtLoginUsername.getText().toString());
        editor.apply();
    }

    /*
    切换线程更新UI
     */
    private void showResponse(final String str){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //在这里进行UI操作，将结果显示到界面上
                showToast(str);
            }
        });
    }



    /**
     * 显示Toast
     *
     * @param msg 提示信息内容
     */
    private void showToast(int msg) {
        if (null != mToast) {
            mToast.setText(msg);
        } else {
            mToast = Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT);
        }

        mToast.show();
    }

    private void showToast(String msg) {
        if(msg == null) msg = "NULL";
        if (null != mToast) {
            mToast.setText(msg);
        } else {
            mToast = Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT);
        }

        mToast.show();
    }
}
